package com.quanliang.org.crawlerquanliang.core;

import com.quanliang.org.crawlerquanliang.pojo.Data;
import com.quanliang.org.crawlerquanliang.utils.ExcelUtil;
import lombok.SneakyThrows;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 写Excel文件线程
 *
 * @author FYM
 * @data 2022/8/27 4:17
 */
public class WriteTask implements Runnable {
    private final HSSFWorkbook wb;
    private final String fileURL;
    private final HSSFSheet sheet;

    public WriteTask(HSSFWorkbook wb, String fileURL, HSSFSheet sheet) {
        this.wb = wb;
        this.fileURL = fileURL;
        this.sheet = sheet;
    }

    @SneakyThrows
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "开始将数据写入Excel中");
        while (!Container.isOver) {
            while (!Container.dataQueue.isEmpty()) {
                Data data = Container.dataQueue.poll();
                //写入一行数据
                assert data != null;
                writeRow(data);
            }
            TimeUnit.MILLISECONDS.sleep(200);
        }
        //任务结束,持久化,关闭流
        try {
            BufferedOutputStream fileOutputStream = new BufferedOutputStream(new FileOutputStream(fileURL));
            wb.write(fileOutputStream);
            fileOutputStream.close();
            System.out.println(Thread.currentThread().getName() + "将所有数据已写入Excel中,任务完成！");
            Container.isEnd = true;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 写一行数据
     */
    private void writeRow(Data data) {
        HSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1);

        row.createCell(0).setCellValue(data.getTitle());
        row.createCell(1).setCellValue(data.getReleaseDate());
        row.createCell(2).setCellValue(data.getReadCount());
        row.createCell(3).setCellValue(data.getPage());
        //插入图片 传入本地文件路径
        //将本地图片传入excel中
        ExcelUtil.insertImg(wb, sheet, row, data.getImgLocal(), sheet.getLastRowNum() + 1);
    }
}
